import { useState, useEffect } from "react";

function Son() {
  // 渲染完毕后开启定时器，组件销毁时清除定时器
  useEffect(() => {
    const timer = setInterval(() => {
      console.log("定时器开启");
    }, 1000);
    return () => {
      clearInterval(timer);
      console.log("定时器关闭");
    };
  });
  return (
    <div style={{ backgroundColor: "red", width: "100%", height: "200px" }}>
      我是子组件
      <hr />
    </div>
  );
}

function Father() {
  const [flag, setFlag] = useState(true);
  return (
    <>
      我是父组件
      <p></p>
      <button onClick={() => setFlag(!flag)}>切换</button>
      <hr />
      <p>下面是子组件</p>
      {flag && <Son />}
    </>
  );
}

export default Father;
